import type { ConfigItem } from "../types/index.d";

export function useFormHook(Config: ConfigItem[], data: Record<string, any>) {
  /**
   * @description 处理表单数据=>接口
   * @return {*}
   */
  let json = {} as Record<string, any>;
  const handleFormData = () => {
    Config.forEach(item => {
      const { prop, type } = item;
      if (["datePicker"].includes(type)) {
        // 处理日期类型字段
        if (data[prop] && data[prop].length > 0) {
          json[prop] = data[prop].join(" - "); // 将日期数组转化为字符串
          return;
        }
      }
      // 剩余类型字段
      json[prop] = data[prop];
    });
    return json;
  };

  /**
   * @description 重置表单数据
   */
  const resetFormData = () => {
    Object.keys(data).forEach(key => {
      // 根据字段类型来决定重置值
      if (typeof data[key] === "string") {
        data[key] = ""; // 字符串类型重置为空字符串
      } else if (typeof data[key] === "number") {
        data[key] = null; // 数字类型重置为 null
      } else if (typeof data[key] === "boolean") {
        data[key] = false; // 布尔类型重置为 false
      } else if (Array.isArray(data[key])) {
        data[key] = []; // 数组类型重置为空数组
      }
    });
  };

  return {
    handleFormData,
    resetFormData
  };
}

export default useFormHook;
